package com.project2.execption;

import com.project2.bean.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

/**
 * @author : bunnyupup
 * @description :
 * @date : Created in 2022/8/16 19:57
 */
@RestControllerAdvice
public class CustomExceptionControllerAdvice {

    @Autowired
    private JavaMailSender mailSender;


    @ExceptionHandler(ValidationException.class)
    public ResultVo validationException(ValidationException exception) {

        return ResultVo.invalidParameter(exception.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    public ResultVo doSystemException(SystemException ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        //  new Result(ex.getCode(),null,ex.getMessage())
        Date date = new Date();

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("764782750@qq.com"); //发件人
        message.setTo("1320694122@qq.com");  //收件人
        message.setSubject("project2异常请需要紧急处理！！！");
        message.setText("你好! "+date+ "   出错代码:"+ex.getCode()+"    "+ex.getCause());
        mailSender.send(message);

        return ResultVo.wrong("系统繁忙中，请稍后再试");
    }

    @ExceptionHandler(BusinessException.class)
    public ResultVo doBusinessException(BusinessException ex){
        // new Result(ex.getCode(),null,ex.getMessage())

        return ResultVo.ok(ex.getMessage(),ex.getCode());
    }
    //除了自定义的异常处理器，保留对Exception类型的异常处理，用于处理非预期的异常
    @ExceptionHandler(doOtherException.class)
    public ResultVo doOtherException(doOtherException ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        //   new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙，请稍后再试！")
        return ResultVo.wrong("系统繁忙，请稍后再试！");
    }
}
